package Leetcode第二期;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : K k
 * @date : 9:42 2020/10/4
 * 给定一个包含 m x n 个元素的矩阵（m 行, n 列），请按照顺时针螺旋顺序，返回矩阵中的所有元素。
 *
 * 示例 1:
 *
 * 输入:
 * [
 *  [ 1, 2, 3 ],
 *  [ 4, 5, 6 ],
 *  [ 7, 8, 9 ]
 * ]
 * 输出: [1,2,3,6,9,8,7,4,5]
 * 示例 2:
 *
 * 输入:
 * [
 *   [1, 2, 3, 4],
 *   [5, 6, 7, 8],
 *   [9,10,11,12]
 * ]
 * 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
 */
public class 螺旋矩阵_54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<>();
        if (matrix.length == 0 || matrix[0].length == 0) {
            return ans;
        }
        int row1 = 0, row2 = matrix.length - 1, col1 = 0, col2 = matrix[0].length - 1;

        while (row1 <= row2 || col1 <= col2) {
            if (row1 <= row2) {
                for (int i = col1; i <= col2; i++) {
                    ans.add(matrix[row1][i]);
                }
            }
            if (col1 <= col2) {
                for (int i = row1 + 1; i <= row2; i++) {
                    ans.add(matrix[i][col2]);
                }
            }
            if (col1 < col2 && row1 < row2) {
                for (int i = col2 - 1; i >= col1; i--) {
                    ans.add(matrix[row2][i]);
                }
                for (int i = row2 - 1; i > row1; i--) {
                    ans.add(matrix[i][col1]);
                }
            }
            col1++;
            col2--;
            row1++;
            row2--;
        }
        return ans;
    }

    public static void main(String[] args) {
        螺旋矩阵_54 x = new 螺旋矩阵_54();
       /* System.out.println(x.spiralOrder(new int[][]{
                {1,2,3,4},{5,6,7,8},{9,10,11,12}}));*/
        System.out.println(x.spiralOrder(new int[][]{
                {6, 9, 7}}));
    }
}
